package com.jbit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jbit.common.RespBean;
import com.jbit.common.ResultCode;
import com.jbit.common.condition.UserRegisterCondition;
import com.jbit.exception.BusinessException;
import com.jbit.pojo.User;
import com.jbit.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "注册之前检查用户是否存在")
    @GetMapping("/ckusr")
    public RespBean checkUser(String username) {
        if (StringUtils.isEmpty(username)) {

            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getCode(), ResultCode.PARAM_IS_BLANK.getMessage());
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);

        User user = userService.getOne(wrapper);
        if (user != null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(), ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }

        return RespBean.success();
    }

    @ApiOperation(value = "使用邮箱注册")
    @PostMapping("/registry")
    public RespBean registry(@RequestBody UserRegisterCondition condition) {
        boolean flag = userService.userRegister(condition);
        if (flag) {
            return RespBean.success();
        }
        return RespBean.error();
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public RespBean login(@RequestParam("username") String username, @RequestParam("password") String password,
                          HttpServletRequest request) {

       return userService.login(username,password,request);
    }
}
